package com.zqq.demo.viewmodel

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zqq.base.BaseViewModel
import com.zqq.base.utils.LogUtils
import com.zqq.demo.net.Repository
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

class MainViewModel(application: Application):BaseViewModel(application) {

    val repository by lazy { Repository.instance }

    val list = MutableLiveData<MutableList<String>>()
    var selectIndex = MutableLiveData<Int>(0)
    var url = MutableLiveData<String>("")

    fun getList(){
        viewModelScope.launch {

            requestState.value = 1

            delay(5000)

            repository.getList().collect(){
                requestState.value = 0
                JSONObject(it).optJSONObject("data")?.optJSONArray("datas")?.let {
                    val mutableList = mutableListOf<String>()
                    for (i in 0 until it.length()){
                        mutableList.add(it.optString(i))
                    }
                    list.postValue(mutableList)
                }
            }
        }
    }

}